package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.common.PageResult5;
import com.itheima.common.Result3;
import com.itheima.entity.Articles;
import com.itheima.entity.User;
import com.itheima.mapper.ArticlesMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.service.ArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ArticlesServiceImpl extends ServiceImpl<ArticlesMapper, Articles> implements ArticlesService {
    @Autowired
    private ArticlesMapper articlesMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageResult5 findPage(Integer page, Integer pagesize, String keyword, Integer state) {
        PageResult5 pageResult = new PageResult5();
        IPage<Articles> p = new Page<>(page, pagesize);
        LambdaQueryWrapper<Articles> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(keyword != null, Articles::getTitle, keyword).eq(state != null, Articles::getState, state);
        IPage<Articles> articlesIPage = articlesMapper.selectPage(p, wrapper);
        List<Articles> records = articlesIPage.getRecords();
        for (Articles record : records) {
            User user = userMapper.selectById(record.getCreatorID());
            record.setUsername(user.getUsername());
        }
        pageResult.setCounts((int) articlesIPage.getTotal());
        pageResult.setItems(records);
        pageResult.setPages((int) articlesIPage.getPages());
        pageResult.setPagesize(pagesize);
        pageResult.setPage(page);
        return pageResult;
    }

    @Override
    public void add(Articles articles, String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, username);
        User user = userMapper.selectOne(wrapper);
        articles.setCreatorID(user.getId().intValue());
        articles.setState(1);
        articles.setCreateTime(new Date());
        articles.setVisits(0);
        articlesMapper.insert(articles);
    }

    @Override
    public Result3 updateState(Integer id, Integer state) {
        Articles articles = articlesMapper.selectById(id);
        articles.setState(state);
        articlesMapper.updateById(articles);
        return new Result3(true);
    }
}
